import os
import time

from .cfg.Nvm_FpHead import Nvm_FpHead
from .cfg.Nvm_Global import *
from .Nvm_String import Nvm_Str
from .Nvm_Book import Nvm_Excel


class Nvm_Task(object):
    mmsg = 0
    output_log = 0
    makeinfo = ""

    def __init__(self):
        self.mmsg = []
        self.nvm_string = Nvm_Str()
        self.nvm_fphead = Nvm_FpHead()

    def NvmTaskMkDir(self, fileName):
        self.nvm_string.NvmRdir(fileName)
        self.nvm_string.NvmMkdir(fileName)

    def NvmTaskMklog(self):
        log_path = os.getcwd() + r'\output\components\Nvm\log.txt'
        # self.output_log = open(log_path, 'w', encoding='utf-8')
        self.makeinfo = self.nvm_fphead.headinfo % (self.excel_name, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        # self.output_log.write(self.makeinfo)
        # self.output_log.close()

    def NvmTaskSetExcelName(self, excel_path):
        temp_list = excel_path.split('/')
        self.excel_name = temp_list[len(temp_list) - 1]

    def NvmTaskGetDid(self, mb: Nvm_Excel, startline, endline):
        if endline == -1:
            endline = mb.sheet.nrows
        for i in range (startline, endline):
            mesname, namecanuse = self._NvmTaskChangeInfo(mb.NvmExcelGetData(i, Nvm_Gloable.def_didname))
            if namecanuse == False:
                # self.output_log.write("%d, %d fmt error\n" % (i, Nvm_Gloable.def_didname))
                print("%d, %d fmt error\n" % (i, Nvm_Gloable.def_didname))
            index = self._NvmTaskFindMes(mesname)
            if index == -1:
                mt = Nvm_Mes()
                mt.name = mesname
                mt.name_c = self._NvmTaskRemoveEscape(mb.NvmExcelGetData(i, Nvm_Gloable.def_didnamec))
                mt.did = mb.NvmExcelGetData(i, Nvm_Gloable.def_didnum)
                bytedata = mb.NvmExcelGetData(i, Nvm_Gloable.def_didsize)
                mt.bytesize, bytecanuse = self._NvmTaskGetNum(bytedata)
                if bytecanuse == False:
                    # self.output_log.write("%d, %d fmt error\n" % (i, Nvm_Gloable.def_didsize))
                    print("%d, %d fmt error\n" % (i, Nvm_Gloable.def_didsize))
                mt.defaultvalue = 0
                mt.testvalue = 0
                self.mmsg.append(mt)
                index = self._NvmTaskFindMes(mesname)
            self._NvmTaskAddMes(mb, i, index)
        # self.output_log.close()

    def NvmTaskToFile(self):
        self.nvm_string.NvmMkdir(r'NVM\cfg')
        self.nvm_string.NvmMkdir(r'NVM\inc')
        self.nvm_string.NvmMkdir(r'NVM\src')

        path = os.getcwd() + '\output\\'
        
        fpcfg = open(path+r'NVM\cfg\Nvm_al_cfg.h', 'w', encoding='utf-8')

        fpdatah = open(path+r'NVM\inc\Nvm_data.h', 'w', encoding='utf-8')
        fpdatac = open(path+r'NVM\src\Nvm_data.c', 'w', encoding='utf-8')

        fpfuncrh = open(path+r'NVM\inc\Nvm_fun_get.h', 'w', encoding='utf-8')
        fpfuncrc = open(path+r'NVM\src\Nvm_func_get.c', 'w', encoding='utf-8')

        fpfuncwh = open(path+r'NVM\inc\Nvm_fun_set.h', 'w', encoding='utf-8')
        fpfuncwc = open(path+r'NVM\src\Nvm_func_set.c', 'w', encoding='utf-8')

        fp_bosch_set_h = open(path+r'NVM\inc\Nvm_func_bosch_set_did.h', 'w', encoding='utf-8')
        fp_bosch_set_c = open(path+r'NVM\src\Nvm_func_bosch_set_did.c', 'w', encoding='utf-8')

        fp_bosch_set_mgr_h = open(path+r'NVM\inc\Nvm_func_bosch_set_did_mgr.h', 'w', encoding='utf-8')
        fp_bosch_set_mgr_c = open(path+r'NVM\src\Nvm_func_bosch_set_did_mgr.c', 'w', encoding='utf-8')

        fp_bosch_get_h = open(path+r'NVM\inc\Nvm_func_bosch_get_did.h', 'w', encoding='utf-8')
        fp_bosch_get_c = open(path+r'NVM\src\Nvm_func_bosch_get_did.c', 'w', encoding='utf-8')

        fp_bosch_get_mgr_h = open(path+r'NVM\inc\Nvm_func_bosch_get_did_mgr.h', 'w', encoding='utf-8')
        fp_bosch_get_mgr_c = open(path+r'NVM\src\Nvm_func_bosch_get_did_mgr.c', 'w', encoding='utf-8')

        fp6 : int
        if Nvm_Gloable.def_testonoff == "1":
            fp6 = open(path+r'NVM/testvalue.txt', "w", encoding='utf-8')
            fp6.write(self.makeinfo)

        # 文件生成说明
        fpcfg.write(self.makeinfo)
        fpdatah.write(self.makeinfo)
        fpdatac.write(self.makeinfo)
        fpfuncrh.write(self.makeinfo)
        fpfuncrc.write(self.makeinfo)
        fpfuncwh.write(self.makeinfo)
        fpfuncwc.write(self.makeinfo)
        fp_bosch_set_h.write(self.makeinfo)
        fp_bosch_set_c.write(self.makeinfo)
        fp_bosch_set_mgr_h.write(self.makeinfo)
        fp_bosch_set_mgr_c.write(self.makeinfo)
        fp_bosch_get_h.write(self.makeinfo)
        fp_bosch_get_c.write(self.makeinfo)
        fp_bosch_get_mgr_h.write(self.makeinfo)
        fp_bosch_get_mgr_c.write(self.makeinfo)

        # 文件头
        fpcfg.write(self.nvm_fphead.cfghead)
        fpdatah.write(self.nvm_fphead.datahdef)
        fpdatac.write(self.nvm_fphead.datacdef)
        fpfuncrh.write(self.nvm_fphead.GetHeadDef("Nvm_func_get"))
        fpfuncrc.write(self.nvm_fphead.GetcDef("Nvm_func_get"))
        fpfuncwh.write(self.nvm_fphead.GetHeadDef("Nvm_func_set"))
        fpfuncwc.write(self.nvm_fphead.GetcDef("Nvm_func_set"))
        fp_bosch_set_h.write(self.nvm_fphead.GetHeadDef("Nvm_func_bosch_set_did"))
        fp_bosch_set_c.write(self.nvm_fphead.GetcDef("Nvm_func_bosch_set_did"))
        fp_bosch_set_mgr_h.write(self.nvm_fphead.GetHeadDef("Nvm_func_bosch_set_did_mgr"))
        fp_bosch_set_mgr_c.write(self.nvm_fphead.GetcDef("Nvm_func_bosch_set_did_mgr"))
        fp_bosch_get_h.write(self.nvm_fphead.GetHeadDef("Nvm_func_bosch_get_did"))
        fp_bosch_get_c.write(self.nvm_fphead.GetcDef("Nvm_func_bosch_get_did"))
        fp_bosch_get_mgr_h.write(self.nvm_fphead.GetHeadDef("Nvm_func_bosch_get_did_mgr"))
        fp_bosch_get_mgr_c.write(self.nvm_fphead.GetcDef("Nvm_func_bosch_get_did_mgr"))
        # 写文件主要内容
        fp_bosch_set_mgr_h.write("#include\"Nvm_func_bosch_set_did.h\"\n\n")
        fp_bosch_set_mgr_h.write("EXTERN boolean set_by_did(uint32 did, uint8* data,uint16* len);\n")

        fp_bosch_set_mgr_c.write("boolean set_by_did(uint32 did, uint8* data,uint16* len){\n")
        fp_bosch_set_mgr_c.write("\tswitch (did) {\n")

        fp_bosch_get_mgr_h.write("#include\"Nvm_func_bosch_get_did.h\"\n\n")
        fp_bosch_get_mgr_h.write("EXTERN boolean get_by_did(uint32 did, uint8* data,uint16* len);\n")

        fp_bosch_get_mgr_c.write("boolean get_by_did(uint32 did, uint8* data,uint16* len){\n")
        fp_bosch_get_mgr_c.write("\tswitch (did) {\n")

        strdatah1 =""
        strdatah2 =""
        strdatac1 =""
        strdatac2 =""

        for i in range(len(self.mmsg)):
            fpcfg.write("// %s \n// %s \n// DID %s \n" % (self.mmsg[i].name_c, self.mmsg[i].name, self.mmsg[i].did))  # 添加DID注释信息
            fpcfg.write("typedef union\n{\n\tuint8 data[%d];\n\tstruct\n\t{\n" % (self.mmsg[i].bytesize))
            strdatah1 += ("// DID %s \n" % (self.mmsg[i].did))
            strdatac1 += ("// DID %s \n" % (self.mmsg[i].did))
            strdatah2 += ("// DID %s \n" % (self.mmsg[i].did))
            strdatac2 += ("// DID %s \n" % (self.mmsg[i].did))
            fpfuncrh.write("// DID %s \n" % (self.mmsg[i].did))
            fpfuncrc.write("// DID %s \n" % (self.mmsg[i].did))
            fpfuncwh.write("// DID %s \n" % (self.mmsg[i].did))
            fpfuncwc.write("// DID %s \n" % (self.mmsg[i].did))

            byte_index = 0
            didnametype = "%s_T" % (self.mmsg[i].name)
            didnameread = "nvm_%s_get" % (self.mmsg[i].name)
            didnamewrite = "nvm_%s_set" % (self.mmsg[i].name)
            msgdidname = "msg"
            didname = self.mmsg[i].name
            for j in range(len(self.mmsg[i].msigs)):
                if (byte_index != self.mmsg[i].msigs[j].byte_start):
                    fpcfg.write("\t\t//byte %d\n" % (self.mmsg[i].msigs[j].byte_start))
                    byte_index = self.mmsg[i].msigs[j].byte_start
                if (self.mmsg[i].msigs[j].name == "_"):
                    self.mmsg[i].msigs[j].name = self.mmsg[i].name

                cfgmsgname = "cfg_%s" % (self.mmsg[i].msigs[j].name)
                msgname = self.mmsg[i].msigs[j].name
                msgbs = self.mmsg[i].msigs[j].bit_size
                # print(didnametype,didnameread,didnamewrite,msgdidname,didname,cfgmsgname,msgname,msgbs)
                if msgbs <= 32:
                    if msgbs == 32:
                        fpcfg.write("\t\tuint32 %s;\t// %s\t%s\n" % (cfgmsgname,
                                                                        self.mmsg[i].msigs[j].name_c,
                                                                        self.mmsg[i].msigs[j].info))
                    else:
                        fpcfg.write("\t\tuint32 %s:%d;\t// %s\t%s\n" % (cfgmsgname,
                                                                            msgbs,
                                                                            self.mmsg[i].msigs[j].name_c,
                                                                            self.mmsg[i].msigs[j].info))
                    fpfuncrh.write("EXTERN uint32 Get_%s_%s(void);\n" % (didname, msgname))
                    fpfuncrc.write("uint32 Get_%s_%s(void){\n" % (didname, msgname))
                    fpfuncrc.write("\tuint32 data = %s.%s.%s;\n"%(didnameread, msgdidname, cfgmsgname))
                    if (msgbs <= 8):
                        pass
                    elif (msgbs == 16):
                        fpfuncrc.write("\tconv16(data);\n")
                    elif (msgbs == 24):
                        fpfuncrc.write("\tconv24(data);\n")
                    elif (msgbs == 32):
                        fpfuncrc.write("\tconv32(data);\n")
                    else:
                        print ("error special data!!!!")
                    if self.mmsg[i].msigs[j].defaultvalue != None:
                        if self.mmsg[i].msigs[j].minvalue != None and  self.mmsg[i].msigs[j].minvalue != 0:
                            fpfuncrc.write("\tif(data < %d) return %d;\n" % (
                                self.mmsg[i].msigs[j].minvalue,self.mmsg[i].msigs[j].defaultvalue))
                        if self.mmsg[i].msigs[j].maxvalue != None and self.mmsg[i].msigs[j].maxvalue != ((1 << msgbs) -1):
                            fpfuncrc.write("\tif(data > %d) return %d;\n" % (
                                self.mmsg[i].msigs[j].maxvalue,self.mmsg[i].msigs[j].defaultvalue))
                    fpfuncrc.write("\treturn data;\n")
                    fpfuncrc.write("}\n")

                    # funcw
                    fpfuncwh.write("EXTERN boolean Set_%s_%s(uint32 data);\n" % (didname, msgname))
                    fpfuncwc.write("boolean Set_%s_%s(uint32 data){\n" % (didname, msgname))
                    if self.mmsg[i].msigs[j].minvalue != None and self.mmsg[i].msigs[j].minvalue != 0:
                        fpfuncwc.write("\tif(data < %d) return FALSE;\n" % (self.mmsg[i].msigs[j].minvalue))
                    if self.mmsg[i].msigs[j].maxvalue != None and self.mmsg[i].msigs[j].maxvalue != ((1 << 32) - 1):
                        fpfuncwc.write("\tif(data > %d) return FALSE;\n" % ( self.mmsg[i].msigs[j].maxvalue))
                    if (msgbs <= 8):
                        pass
                    elif (msgbs == 16):
                        fpfuncwc.write("\tconv16(data);\n")
                    elif (msgbs == 24):
                        fpfuncwc.write("\tconv24(data);\n")
                    elif (msgbs == 32):
                        fpfuncwc.write("\tconv32(data);\n")
                    else:
                        print ("error special data!!!!")
                    fpfuncwc.write("\t%s.%s.%s = data;\n\treturn TRUE;\n" % (didnamewrite, msgdidname, cfgmsgname))
                    fpfuncwc.write("}\n")

                else:
                    if (msgbs % 8 == 0):
                        msgbs = int(msgbs / 8)
                    else:
                        msgbs = int(msgbs / 8)+1
                    # funcr
                    fpcfg.write("\t\tuint8 %s[%d];// %s\t %s\n" % (
                            cfgmsgname, msgbs,self.mmsg[i].msigs[j].name_c,self.mmsg[i].msigs[j].info))

                    fpfuncrh.write("EXTERN uint8* Get_%s_%s(void);\n" % (didname, msgname))
                    fpfuncrc.write("uint8* Get_%s_%s(void){\n" % (didname, msgname))
                    fpfuncrc.write("\treturn %s.%s.%s;\n" % (didnameread, msgdidname, cfgmsgname))
                    fpfuncrc.write("}\n")
                    # funcw
                    fpfuncwh.write("EXTERN boolean Set_%s_%s(uint8* data);\n" % (didname, msgname))
                    fpfuncwc.write("boolean Set_%s_%s(uint8* data){\n" % (didname, msgname))
                    fpfuncwc.write("\tif(data == NULL ) return FALSE;\n")
                    fpfuncwc.write("\tmemcpy(%s.%s.%s,data,%d);return TRUE;\n"%(didnamewrite, msgdidname, cfgmsgname,msgbs))
                    fpfuncwc.write("}\n")

            fpcfg.write("\t}%s;\n" % (msgdidname))
            fpcfg.write("}%s;\n" % (didnametype))

            fpcfg.write("\n")
            fpfuncrh.write("\n")
            fpfuncrc.write("\n")

            # data
            strdatah1 += ("EXTERN %s %s;\n" % (didnametype, didnameread))
            strdatac1 += ("%s %s;\n" % (didnametype, didnameread))

            strdatah2 += ("EXTERN %s %s;\n" % (didnametype, didnamewrite))
            strdatac2 += ("%s %s;\n" % (didnametype, didnamewrite))

            # bosch-set-did
            fp_bosch_set_h.write("// DID %s %s \n" % (self.mmsg[i].did,didname))
            fp_bosch_set_c.write("// DID %s %s\n" % (self.mmsg[i].did,didname))
            fp_bosch_set_h.write("EXTERN boolean BOSCH_Set_DID_%s(uint8* data,uint16* len);\n" % (self.mmsg[i].did))
            fp_bosch_set_c.write("boolean BOSCH_Set_DID_%s(uint8* data,uint16* len){\n" % (self.mmsg[i].did))
            fp_bosch_set_c.write("\tif((data == NULL) || (len == NULL) || (*len != %d)) return FALSE;\n"%(self.mmsg[i].bytesize))
            fp_bosch_set_c.write("\tmemcpy(%s.data,data,%d); return TRUE;\n" % (didnameread,self.mmsg[i].bytesize))
            fp_bosch_set_c.write("}\n")

            # bosch-get-did
            fp_bosch_get_h.write("// DID %s %s \n" % (self.mmsg[i].did,didname))
            fp_bosch_get_c.write("// DID %s %s\n" % (self.mmsg[i].did,didname))
            fp_bosch_get_h.write("EXTERN boolean BOSCH_Get_DID_%s(uint8* data,uint16* len);\n" % (self.mmsg[i].did))
            fp_bosch_get_c.write("boolean BOSCH_Get_DID_%s(uint8* data,uint16* len){\n" % (self.mmsg[i].did))
            fp_bosch_get_c.write("\tif((data == NULL) || (len == NULL)) return FALSE;\n")
            fp_bosch_get_c.write("\tmemcpy(data,%s.data,%d); *len = %d; return TRUE;\n" % (didnamewrite,self.mmsg[i].bytesize,self.mmsg[i].bytesize))
            fp_bosch_get_c.write("}\n")

            # funcdidmgr
            fp_bosch_set_mgr_c.write("\t\tcase %s :\n"%self.mmsg[i].did)
            fp_bosch_set_mgr_c.write("\t\t\treturn BOSCH_Set_DID_%s(data,len);\n"%self.mmsg[i].did)

            fp_bosch_get_mgr_c.write("\t\tcase %s :\n"%self.mmsg[i].did)
            fp_bosch_get_mgr_c.write("\t\t\treturn BOSCH_Get_DID_%s(data,len);\n"%self.mmsg[i].did)

            # test
            if Nvm_Gloable.def_testonoff == "1":
                fp6.write("// %s \n// %s \n// DID %s \n// byte size:%d \n" % (
                self.mmsg[i].name_c, self.mmsg[i].name, self.mmsg[i].did, self.mmsg[i].bytesize))
                fmtx = "%%0%dx" % (self.mmsg[i].bytesize * 2)
                data = fmtx % self.mmsg[i].testvalue
                datal = []
                for n in range(self.mmsg[i].bytesize):
                    datal.append(data[(self.mmsg[i].bytesize - n - 1) * 2])
                    datal.append(data[(self.mmsg[i].bytesize - n - 1) * 2 + 1])
                # print(datal)
                data = "".join(datal)
                # print(data)
                fp6.write("// value-fmt0: %s\n" % data)
                data = ""
                for itmp in range(self.mmsg[i].bytesize):
                        data += "0x%c%c,"%(datal[itmp*2],datal[itmp*2+1])
                fp6.write("// value-fmt1: %s\n" % data)
                data = ""
                for itmp in range(self.mmsg[i].bytesize):
                    data += "0x%c%c " % (datal[itmp * 2], datal[itmp * 2 + 1])
                fp6.write("// value-fmt2: %s\n" % data)
                fp6.write("\n\n")

        fp_bosch_set_mgr_c.write("\t\tdefault:\n\t\t\treturn FALSE;\n\t}\n}\n")
        fp_bosch_get_mgr_c.write("\t\tdefault:\n\t\t\treturn FALSE;\n\t}\n}\n")

        fpdatah.write(strdatah1)
        fpdatah.write("\n\n")
        fpdatah.write(strdatah2)
        fpdatac.write("\n\n#pragma pack(push)\n#pragma pack(1)\n\n#pragma ghs section bss=\".kam_al_bss\"")
        fpdatac.write(strdatac1)
        fpdatac.write("\n\n\n#pragma ghs section bss=default\n\n\n\n")
        fpdatac.write(strdatac2)
        fpdatac.write("\n\n\n#pragma pack(pop)\n\n")

        fpcfg.write("\n#endif\n")
        fpdatah.write("\n#endif\n")
        fpdatac.write("\n#endif\n")

        fpfuncrh.write("\n#endif\n")
        fpfuncrc.write("\n#endif\n")
        fpfuncwh.write("\n#endif\n")
        fpfuncwc.write("\n#endif\n")

        fp_bosch_set_h.write("\n#endif\n")
        fp_bosch_set_c.write("\n#endif\n")
        fp_bosch_set_mgr_h.write("\n#endif\n")
        fp_bosch_set_mgr_c.write("\n#endif\n")

        fp_bosch_get_h.write("\n#endif\n")
        fp_bosch_get_c.write("\n#endif\n")
        fp_bosch_get_mgr_h.write("\n#endif\n")
        fp_bosch_get_mgr_c.write("\n#endif\n")

        fpcfg.close()
        fpdatah.close()
        fpdatac.close()

        fpfuncrh.close()
        fpfuncrc.close()
        fpfuncwh.close()
        fpfuncwc.close()

        fp_bosch_set_h.close()
        fp_bosch_set_c.close()
        fp_bosch_set_mgr_h.close()
        fp_bosch_set_mgr_c.close()

        fp_bosch_get_h.close()
        fp_bosch_get_c.close()
        fp_bosch_get_mgr_h.close()
        fp_bosch_get_mgr_c.close()

        if Nvm_Gloable.def_testonoff == "1":
            fp6.close()

    def _NvmTaskChangeInfo(self, data):
        data = data.strip()  # 把字符串(str)的头和尾的空格，以及位于头尾的\n \t之类给删掉
        for i in range(len(data)):
            if data[i] not in Nvm_Gloable.str_can_use:
                data = data.replace(data[i], '_')
        while (data.find('__') != -1):
            data = data.replace('__', '_')
        if (len(data) == 0):
            return '', False
        return data, True
    
    def _NvmTaskFindMes(self, name):
        for i in range(len(self.mmsg)):
            if self.mmsg[i].name == name:
                return i
        return -1
    
    def _NvmTaskRemoveEscape(self, data):
        data = data.replace('\n', '\t')
        data = data.strip()
        return data
    
    def _NvmTaskGetNum(self, data):
        data = data.strip()
        if data == "" or data == "-":
            return None, False
        if self._NvmTaskIsNum(data):
            if(int(float(data)) - float(data)) == 0:
                return int(float(data)), True
            else:
                return -1, False
        return -1, False

    def _NvmTaskIsNum(self, data):
        try:
            float(data)
            return True
        except ValueError:
            pass
        return False
    
    def _NvmTaskAddMes(self, mb: Nvm_Excel, line: int, index: int):
        ms = Nvm_MSig()
        ms.name, namecanuse = self._NvmTaskChangeInfo(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsigname))
        if namecanuse == False:
            # self.output_log.write("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didsigname))
            print("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didsigname))
        ms.name = self.mmsg[index]._NvmMesCheckName(ms.name)

        ms.name_c = self._NvmTaskRemoveEscape(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsignamec))
        
        byteinfo = self._NvmTaskSplitData(mb.NvmExcelGetData(line, Nvm_Gloable.def_didbyte))
        if byteinfo[3] == False:
            # self.output_log.write("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didbyte))
            print("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didbyte))
        ms.byte_start = byteinfo[0]
        ms.byte_size = byteinfo[1]
        if byteinfo[2] == True:
            ms.byte_start = 0
            ms.byte_size = self.mmsg[index].bytesize

        bitinfo = self._NvmTaskSplitData(mb.NvmExcelGetData(line, Nvm_Gloable.def_didbit))
        if byteinfo[3] == False:
            # self.output_log.write("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didbit))
            print("%d, %d fmt error\n" % (line, Nvm_Gloable.def_didbit))
        ms.bit_start = bitinfo[0]
        ms.bit_size = bitinfo[1]
        if bitinfo[2] == True:
            ms.bit_start = 0
            ms.bit_size = ms.byte_size * 8

        ms.info = self._NvmTaskRemoveEscape(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsiginfo))
        ms.minvalue, _ = self._NvmTaskGetNum(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsigmin))
        if ms.minvalue != None and ms.minvalue < 0:
            # self.output_log.write("line %d sig最小值:%d非法\n" % (line, Nvm_Gloable.def_didsigmin))
            print("line %d 最小值:%d非法\n" % (line, Nvm_Gloable.def_didsigmin))
            ms.minvalue = None

        ms.maxvalue, _ = self._NvmTaskGetNum(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsigmax))
        if ms.maxvalue != None and (ms.maxvalue < 0 or ms.maxvalue >= (1 << ms.bit_size)):
            # self.output_log.write("line %d sig最大值:%d非法\n" % (line, Nvm_Gloable.def_didsigmax))
            print("line %d 最大值:%d非法\n" % (line, Nvm_Gloable.def_didsigmax))
            ms.maxvalue = None

        ms.testvalue, _ = self._NvmTaskGetNum(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsigtestvalue))
        if ms.testvalue != None and ms.testvalue < 0:
            # self.output_log.write("line %d sig测试值:%d非法\n" % (line, Nvm_Gloable.def_didsigtestvalue))
            print("line %d 测试值:%d非法\n" % (line, Nvm_Gloable.def_didsigtestvalue))
            ms.testvalue = None

        ms.defaultvalue, _ = self._NvmTaskGetNum(mb.NvmExcelGetData(line, Nvm_Gloable.def_didsigdefault))
        if ms.defaultvalue != None and ms.defaultvalue == -1:
            # self.output_log.write("line %d sig默认值:%d非法\n" % (line, Nvm_Gloable.def_didsigdefault))
            print("line %d 默认值:%d非法\n" % (line, Nvm_Gloable.def_didsigdefault))
            ms.defaultvalue = None

        if ms.minvalue != None:
            if ms.defaultvalue != None:
                if ms.defaultvalue < ms.minvalue:
                    # self.output_log.write("line %d sig 默认值小于最小值\n" % (line))
                    print("line %d sig 默认值小于最小值\n" % (line))
            if ms.testvalue != None:
                if ms.testvalue < ms.minvalue:
                    # self.output_log.write("line %d sig 测试值小于最小值\n" % (line))
                    print("line %d sig 测试值小于最小值" % (line))
        if ms.maxvalue != None:
            if ms.defaultvalue != None:
                if ms.defaultvalue > ms.maxvalue:
                    # self.output_log.write("line %d sig 默认值大于最大值\n" % (line))
                    print("line %d sig 默认值大于最大值" % (line))
            if ms.testvalue != None:
                if ms.testvalue > ms.maxvalue:
                    # self.output_log.write("line %d sig 测试值大于最大值\n" % (line))
                    print("line %d sig is 测试值大于最大值" % (line))
        if ms.defaultvalue != None:
            if ms.defaultvalue >= 1 << ms.bit_size:
                # self.output_log.write("line %d sig 默认值大于可表达值\n" % (line))
                print("line %d sig 默认值大于可表达值" % (line))
        if ms.testvalue != None:
            if ms.testvalue >= 1 << ms.bit_size:
                # self.output_log.write("line %d sig 测试值大于可表达值\n" % (line))
                print("line %d sig  测试值大于可表达值" % (line))
        if self.mmsg[index].bitindex != ms.byte_start * 8 + ms.bit_start:
            # self.output_log.write("error line %d sig 数据不连续\n" % (line))
            print("line %d sig 数据不连续" % (line))

        if Nvm_Gloable.def_defaultonoff != '1':
            ms.defaultvalue = None
        if Nvm_Gloable.def_testonoff != '1':
            ms.testvalue = None
        self.mmsg[index].bitindex = ms.byte_start * 8 + ms.bit_start + ms.bit_size
        self.mmsg[index].msigs.append(ms)
        if ms.defaultvalue != None:
            self.mmsg[index].defaultvalue |= (ms.defaultvalue << (ms.byte_start * 8 + ms.bit_start))
        if ms.testvalue != None:
            if ms.bit_size == 16 :
                ms.testvalue = ((ms.testvalue & 0xFF) << 8) + ((ms.testvalue & 0xFF00) >> 8)
            elif ms.bit_size == 24 :
                ms.testvalue = ((ms.testvalue & 0xFF) << 16) + ((ms.testvalue & 0xFF00))  + ((ms.testvalue & 0xFF0000)>> 16)
            elif ms.bit_size == 32:
                ms.testvalue = ((ms.testvalue & 0xFF) << 24) + ((ms.testvalue & 0xFF00) << 8) + ((ms.testvalue & 0xFF0000) >> 8) + ((ms.testvalue & 0xFF000000) >> 24)
            self.mmsg[index].testvalue |= (ms.testvalue << (ms.byte_start * 8 + ms.bit_start))

    def _NvmTaskSplitData(self, data:str):
        if data == 'All' or data == 'ALL':
            return 0, 0, True, True
        if data.find('-') != -1:
            index1 = data.index('-')
            n = int(data[0:index1])
            m = int(data[index1+1:])
            return n, m-n+1, False , True
        if self._NvmTaskIsNum(data) == True:
            return int(float(data)), 1, False, True
        return -1, -1, False, False 
    
    def NvmTaskGetDidData(self):
        return self.mmsg

class Nvm_Mes(object):
    name: str
    name_c: str
    did: str
    bytesize: str
    msigs: str
    defaultvalue = 0
    testvalue = 0
    bitindex = 0

    def __init__(self):
        self.msigs = []
        self.mes_str = Nvm_Str()

    def _NvmMesCheckName(self, name: str):
        if self._NvmMesFindSig(name) == -1:
             return name
        basename = self.mes_str._NvmStrCheckBaseName(name)
        index = 1
        while (self._NvmMesFindSig(basename + "_" + str(index)) != -1):
            index = index + 1
        else:
            return basename + "_" + str(index)

    def _NvmMesFindSig(self, name: str) -> int:
        for i in range(len(self.msigs)):
            if (self.msigs[i].name == name):
                return i
        return -1

class Nvm_MSig(object):
    name: str
    name_c: str
    byte_start: int
    byte_size: int
    bit_start: int
    bit_size: int
    info: str
    minvalue = 0
    maxvalue = 0
    defaultvalue = 0
    testvalue = 0
